package com.atguigu.Flink.state;

import com.atguigu.Flink.POJO.WindSpeedSensor;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.Comparator;

public class Flink07_KeyedMapState {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //需求：检测每种传感器的风速，如果连续的两个风速差值为10，就输出报警
        SingleOutputStreamOperator<WindSpeedSensor> ds = env.socketTextStream("hadoop102", 8888)
                .map(
                        line -> {
                            String[] split = line.split(",");
                            return new WindSpeedSensor(split[0], Integer.valueOf(split[1]), Long.valueOf(split[2]));
                        }
                );
            //去掉每种传感器重复的风速值
                ds.keyBy(
                        k->k.getId()
                ).process(
                        new KeyedProcessFunction<String, WindSpeedSensor, String>() {
                            //声明map状态，将speed作为key值，value值随意
                            private MapState<Integer,Integer> mapState;

                            @Override
                            public void open(Configuration parameters) throws Exception {
                                //初始化状态
                                MapStateDescriptor mapStateDescriptor = new MapStateDescriptor("map", Types.INT, Types.INT);
                                mapState = getRuntimeContext().getMapState(mapStateDescriptor);
                            }

                            @Override
                            public void processElement(WindSpeedSensor windSpeedSensor, KeyedProcessFunction<String, WindSpeedSensor, String>.Context context, Collector<String> collector) throws Exception {
                                //将当前数据的风速值放入状态中
                                mapState.put(windSpeedSensor.getSpeed(),windSpeedSensor.getSpeed());
                                collector.collect(windSpeedSensor.getId() + "风速传感器的风速记录： " + mapState.keys());

                            }
                        }
                ).print();



        try {
            env.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
